import { add, list, updateStatus } from '@/services/discount/coupon';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, Image, message } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import EditModal from './components/EditModal';

const formatterTime = (val: string | undefined) => {
  return val ? moment(val).format('YYYY-MM-DD') : '';
};

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleSave = async (fields: DISCOUNT.Coupon) => {
  const hide = message.loading('正在保存');
  try {
    await add({ ...fields });
    hide();
    message.success('Added successfully');
    return true;
  } catch (error) {
    hide();
    message.error('Adding failed, please try again!');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [editModalOpen, handleEditModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();

  const columns: ProColumns<DISCOUNT.Coupon>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: <FormattedMessage id="pages.photo" defaultMessage="Photo" />,
      valueType: 'textarea',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Image
            width={80}
            src={record.image?.url + '&width=500&height=500'}
            fallback=""
          />
        );
      },
    },
    {
      title: '使用规则',
      dataIndex: 'rule',
      valueType: 'textarea',
      width: 150,
      hideInSearch: true,
      hideInForm: true,
      render: (_, entity) => {
        return (
          <>
            满 {entity.fullMoney} 元减 {entity.money} 元
          </>
        );
      },
    },
    {
      title: '有效时间',
      dataIndex: 'effectiveTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
      render: (_, entity) => {
        return (
          <>
            {formatterTime(entity.startTime)} - {formatterTime(entity.endTime)}
          </>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '禁用',
          status: 'Default',
        },
        1: {
          text: '启用',
          status: 'Success',
        },
        2: {
          text: '废弃',
          status: 'Error',
        },
      },
    },
    {
      title: <FormattedMessage id="pages.description" defaultMessage="Description" />,
      dataIndex: 'description',
      valueType: 'textarea',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: <FormattedMessage id="pages.createDate" defaultMessage="Create date" />,
      dataIndex: 'createDate',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: <FormattedMessage id="pages.option" defaultMessage="Operating" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="enabled"
          onClick={async () => {
            try {
              console.log(record.status);
              await updateStatus({
                id: record.id,
                status: record.status === 1 ? 0 : 1,
              });
              message.success('Configuration is successful');
              if (actionRef.current) {
                actionRef.current.reload();
              }
            } catch (error) {
              message.error('Configuration failed, please try again!');
            }
          }}
        >
          {record.status === 1 ? '禁用' : '启用'}
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<DISCOUNT.Coupon, API.PageParams>
        headerTitle="优惠券列表"
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleEditModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={list}
        columns={columns}
      />
      <EditModal
        onSubmit={async (value) => {
          console.log(value);
          let success = await handleSave(value);
          if (success) {
            handleEditModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        setEditModalOpen={async (open) => {
          if (!open) {
            setCurrentRow(undefined);
          }
          handleEditModalOpen(open);
        }}
        editModalOpen={editModalOpen}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default TableList;
